package stack;

import org.junit.Test;

import java.util.Stack;

public class PostfixExpression {
    @Test
    public void test(){
         //(3+4)*5-6
          String expression="34 2 + 5 * 6 -";
//          String a=expression.substring(2,3);
//        System.out.println(a);
//        System.out.println(a==" ");
//        System.out.println(a.equals(" "));
         calPostExpression(expression);
    }
    public void calPostExpression(String expression){
        //Stack<String> operStack = new Stack<>();
        Stack<Integer> stack = new Stack<>();
        PostUtil postUtil = new PostUtil();
        int index=0;
        String currentChar="";
        while(true){
            currentChar=expression.substring(index,index+1);
            if (postUtil.isOper(currentChar)){
                //当前字符为操作符,则弹出栈中的两个数字进行计算,然后将计算结果压回栈中
                Integer num1 = stack.pop();
                Integer num2 = stack.pop();
                int result = postUtil.cal(num1, num2, currentChar);
                stack.push(result);
                index++;
            }else if (currentChar.equals(" ")){
                index++;
            }else{
                //当前字符是数字则直接进栈,
                String tempChar="";
                do{
                    tempChar+=currentChar;
                    index++;
                    if (index==expression.length())
                        break;
                    currentChar=expression.substring(index,index+1);
                }while(!postUtil.isOper(tempChar) && !currentChar.equals(" "));
                if (currentChar.equals(" "))
                    index++;

                System.out.println("拼接字符串:"+tempChar);


                stack.push(Integer.parseInt(tempChar));
            }
            if (index>expression.length()-1)
                break;
            System.out.println("-----------栈内情况---------");
            stack.forEach(i-> System.out.println(i));
            System.out.println("------------站内-------------");
        }
        System.out.printf("%s的计算结果是:%d",expression,stack.pop());
    }
}
class PostUtil{
    public int cal(int num1,int num2,String oper){
        switch(oper){
            case "+":return num1+num2;
            case "-":return num2-num1;
            case "*":return num1*num2;
            case "/":return num2/num1;
            default:return -1;
        }
    }
    public Boolean isOper(String oper){
        return oper.equals("+")||oper.equals("-")||oper.equals("*")||oper.equals("/");

    }
}